﻿# encoding:utf-8
# 访问数据库 用户
from wxpyImport import *
from db.wxpyDbBase import *

# 取最新的一条数据
def dbGetAccessFrqLatest(dbd, puid, type, resetDb=False):
    sql = "select * from access_frequency where puid = %s and type = %s order by create_time desc limit 1"

    results = None
    try:
        cursor = getCursorColName(dbd, resetDb)
        cursor.execute(sql,(puid, type))
        results = cursor.fetchone()
        cursor.close()
    except Exception as e:
        dealException()
        logError('getAccessFrq err: '+str(e))
        if not resetDb: # 防止死循环
            return dbGetAccessFrqLatest(dbd, puid, type, True)
    
    return results

# 插入一条新的,返回是否成功
def dbAddAccessFrq(dbd, user, type, spendTime, resetDb=False):
    if user.puid is None:
        logError('dbAddAccessFr puid empty: '+str(user.raw))
        return False

    sql = "INSERT INTO access_frequency (spend_time, type, puid, puid_name) VALUES(%s, %s, %s, %s)"

    try:
        nickName = '' if user.nick_name is None else user.nick_name

        cursor = getCursor(dbd, resetDb)
        
        # 存大块聊天记录
        cursor.execute(sql,(spendTime, type, user.puid, nickName))
        dbd.db.commit()
        cursor.close()
    except Exception as e:
        dealException()
        logError('dbAddAccessFr err: '+str(e))
        if not resetDb: # 防止死循环
            return dbAddAccessFrq(dbd, user, type, spendTime, True)
    else:
        logInfo('dbAddAccessFr success: ' + str(user.puid))
        return True

    return False